package com.ljkj.cordial.chat.fragment;


import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.ChatMainActivity;
import com.ljkj.cordial.chat.activity.GroupChatActivity;
import com.ljkj.cordial.chat.adapter.NavChatRecycleAdapter;
import com.ljkj.cordial.chat.base.BaseFragment;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.listener.OnItemRemoveListener;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.ChatItemPop;
import com.nic.view.widget.CommonPopupWindow;
import com.nic.view.widget.RecycleViewDivide;
import com.nic.view.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class NavChatFragment extends BaseFragment {


    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.v_tran)
    View vTran;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    private int lastListSize;
    Unbinder unbinder;
    //    private NavChatAdapter navChatAdapter;
    private NavChatRecycleAdapter navChatRecycleAdapter;
    private boolean isInit = true;
    private WrapContentLinearLayoutManager manager;
    private OnItemRemoveListener mOnItemRemoveListener;

    public static NavChatFragment newInstance(OnItemRemoveListener listener) {
        NavChatFragment fragment = new NavChatFragment();
        fragment.mOnItemRemoveListener = listener;
        return fragment;
    }

    public NavChatFragment() {
        // Required empty public constructor
    }


    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_nav_chat;
    }

    @Override
    public void initView(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);
//        navChatAdapter = new NavChatAdapter();
//        listView.setAdapter(navChatAdapter);
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                ChatContentTable chatContent = (ChatContentTable) parent.getItemAtPosition(position);
//                ChatContentTable.updateSumById(chatContent.getTargetId(), chatContent.getChatType());
//                if (Canstants.GROUP_CHAT == chatContent.getChatType()) {
//                    GroupChatActivity.jumpTo(parent.getContext(), Canstants.GROUP_CHAT,
//                            chatContent.getTargetName(), chatContent.getTargetId(), chatContent.getTargetType());
//                } else if (Canstants.SINGLE_CHAT == chatContent.getChatType()) {
//                    GroupChatActivity.jumpTo(parent.getContext(), Canstants.SINGLE_CHAT,
//                            chatContent.getTargetName(), chatContent.getTargetId(), chatContent.getTargetType());
//                }
//
//            }
//        });
//        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                ChatContentTable chatContent = (ChatContentTable) parent.getItemAtPosition(position);
//                ChatItemPop pop = new ChatItemPop(activity);
//                pop.setData("删除");
//                pop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        DeleteHistoryUtil.getInstance().deleteNavChat(chatContent.getTargetId(), false, false);
//                        queryOfflineData();
//                    }
//                });
//                pop.showBashOfAnchor(view, new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.ALIGN_ABOVE | CommonPopupWindow.LayoutGravity.CENTER_HORI), 0, 14);
//                vTran.setVisibility(View.VISIBLE);
//                vTran.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        vTran.setVisibility(View.GONE);
//                    }
//                });
//                return true;
//            }
//        });
//        listView.setEmptyView(ivEmpty);
        manager = new WrapContentLinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
//        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(activity);
        recycleView.setLayoutManager(manager);
        recycleView.setItemAnimator(null);
        recycleView.addItemDecoration(new RecycleViewDivide(activity, LinearLayoutManager.VERTICAL, 0));
        recycleView.setItemViewCacheSize(20);
        initAdapter();
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    navChatRecycleAdapter.setLoadAccess(true);
//                    refreshVisibleItems();
                } else {
                    navChatRecycleAdapter.setLoadAccess(false);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(-1)) {
                    //top
                } else if (!recyclerView.canScrollVertically(1)) {
                    //bottom
                } else if (dy < 0) {
                    //up
                } else if (dy > 0) {
                    //bottom
                }
            }
        });

    }

    private void initAdapter() {
        navChatRecycleAdapter = new NavChatRecycleAdapter();
        navChatRecycleAdapter.setOnItemClickListener(new NavChatRecycleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position, ChatContentTable item) {
                if (Canstants.GROUP_CHAT == item.getChatType()) {
                    GroupChatActivity.jumpTo(v.getContext(), Canstants.GROUP_CHAT,
                            item.getTargetName(), item.getTargetId(), item.getTargetType(), !TextUtils.isEmpty(item.getLastMsg()) || item.getIsSnapchat() != 0);
                } else if (Canstants.SINGLE_CHAT == item.getChatType()) {
                    GroupChatActivity.jumpTo(v.getContext(), Canstants.SINGLE_CHAT,
                            item.getTargetName(), item.getTargetId(), item.getTargetType(), !TextUtils.isEmpty(item.getLastMsg()) || item.getIsSnapchat() != 0);
                }
            }

            @Override
            public void onItemLongClick(View v, int position, ChatContentTable item) {
                ChatItemPop pop = new ChatItemPop(activity);
                List<String> names = new ArrayList<>();
                names.add("删    除");
                if (item.getIsTOP() == 0) {
                    names.add("置    顶");
                } else {
                    names.add("取消置顶");
                }

                pop.setData(names);
                pop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                        if (pos == 0) {
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                                @Override
                                public void onAction(Object obj) {
                                    if (mOnItemRemoveListener != null)
                                        mOnItemRemoveListener.onItemRemove();
                                }

                                @Override
                                public Object onThreadAction() {
                                    DeleteHistoryUtil.getInstance().deleteNavChat(item.getTargetId(), item.getChatType(), false, false);
                                    return null;
                                }
                            });
                            navChatRecycleAdapter.remove(position);
                            if (navChatRecycleAdapter.getItemCount() == 0) {
                                ivEmpty.setVisibility(View.VISIBLE);
                            } else {
                                ivEmpty.setVisibility(View.GONE);
                            }
                        } else if (pos == 1) {
                            int isTop = item.getIsTOP();
                            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatContentTable>() {
                                @Override
                                public void onAction(ChatContentTable obj) {
                                    if (obj.getIsTOP() == 1) {//置顶
                                        navChatRecycleAdapter.itemMove(position, true);
                                    } else {//取消置顶
                                        navChatRecycleAdapter.cancelTop(position);
                                    }
                                }

                                @Override
                                public ChatContentTable onThreadAction() {
                                    item.setIsTOP(isTop == 0 ? 1 : 0);
                                    if (isTop == 0) {//置顶时间
                                        item.setUpdateTopTime(System.currentTimeMillis());
                                    }
                                    ChatContentTable.update(item);
                                    return item;
                                }
                            });


                        }
                    }
                });
                pop.getPopupWindow().setOnDismissListener(() -> vTran.setVisibility(View.GONE));
                pop.showBashOfAnchor(v, new CommonPopupWindow.LayoutGravity(CommonPopupWindow.LayoutGravity.ALIGN_ABOVE | CommonPopupWindow.LayoutGravity.CENTER_HORI), 0, 14);
                vTran.setVisibility(View.VISIBLE);
                vTran.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        vTran.setVisibility(View.GONE);
                    }
                });

            }
        });
        navChatRecycleAdapter.setOnToTopRefreshListener(() -> recycleView.post(() -> recycleView.smoothScrollToPosition(0)));
        recycleView.setAdapter(navChatRecycleAdapter);
    }


    private void refreshVisibleItems() {
        int visibleItemCount = manager.getChildCount();
        int pastVisibleItem = manager.findFirstVisibleItemPosition();
        navChatRecycleAdapter.setPayLoad(pastVisibleItem, visibleItemCount);
    }

    public void setListView(ListView listView) {
        this.listView = listView;
    }

    public void notifyChat(List<ChatContentTable> list, int... payLoad) {

        if (list == null || list.isEmpty()) {
//            navChatAdapter.clear();
            ivEmpty.setVisibility(View.VISIBLE);
            navChatRecycleAdapter.clear();
            return;
        }
        ivEmpty.setVisibility(View.GONE);
//        Collections.sort(list);
//        navChatAdapter.setList(list);
        navChatRecycleAdapter.setList(list, payLoad);
        lastListSize = list.size();
        recycleView.postDelayed(() -> navChatRecycleAdapter.notifyData(), 300);
        if (activity instanceof ChatMainActivity) {
            ChatMainActivity act = (ChatMainActivity) activity;
            act.setChatSum(ChatContentTable.getUnReadChatSum(list));
        }
    }

    public void setInit(boolean init) {
        isInit = init;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isInit) {
            recycleView.post(() -> queryOfflineData());
        }
    }

    public boolean isInit() {
        return isInit;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void update(ChatContentTable item) {
        if (navChatRecycleAdapter == null) {
            return;
        }
        if (item == null || !DbController.getInstance().getRead().getChatContentTableDao().hasKey(item)) {
            queryOfflineData();
        } else {
            navChatRecycleAdapter.update(item);
            if (navChatRecycleAdapter.getItemCount() > 0) {
                ivEmpty.setVisibility(View.GONE);
            } else {
                ivEmpty.setVisibility(View.VISIBLE);
            }
        }


    }

    public void queryOfflineData(int... payLoad) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<ChatContentTable>>() {
            @Override
            public void onAction(List<ChatContentTable> list) {
                notifyChat(list, payLoad);
            }


            @Override
            public List<ChatContentTable> onThreadAction() {
                return ChatContentTable.query();
            }
        });
    }
}
